package com.fuelindustries.ant.utils;

import java.io.File;
import java.io.IOException;
import java.util.Vector;

import nanoxml.XMLElement;

import com.fuelindustries.ant.FuelAntVariables;
import com.fuelindustries.ant.tasks.Fla;
import com.fuelindustries.ant.tasks.Flp;

public class FLPHelper 
{
	
	
	static public Vector<Fla> getFLPFiles( Flp flp ) throws IOException
	{
		return( getFLPFiles( flp, false ) );
	}
	
	static public Vector<Fla> getFLPFiles( Flp flp, String newflppath ) throws IOException
	{
		Flp f = new Flp();
		f.setBuild( flp.getBuild() );
		f.setFlashPath( flp.getFlashPath() );
		f.setFile( newflppath );
		return( getFLPFiles( f, true ) );
	}
	
	static public Vector<Fla> getFLPFiles( Flp flp, Boolean justpublish ) throws IOException
	{
		Vector<Fla> files = new Vector<Fla>();
		File aFile = new File( flp.getFile() );
		String xmlstr = FileUtils.getContents(aFile);
		
		String basepath = aFile.getParentFile().getAbsolutePath();
		
		basepath = basepath.replace( "\\", "/" );
		
		XMLElement xml = new XMLElement();
		xml.parseString( xmlstr );
		
		String version = xml.getProperty( "version" );
		String flpname = xml.getProperty( "name" );
		
		Vector<XMLElement> children = xml.getChildren();
		
		Fla defaultfla = null;
		
		
		for( int i=0; i<children.size(); i++ )
		{
			XMLElement child = children.get(i);
			String path = child.getProperty("path");
			String profile = child.getProperty( "profile" );
			String def_file = child.getProperty( "def_file" );
			String filetype = child.getProperty( "filetype" );
			String newpath = FileUtils.createAbsolutePathFromRelative(basepath, path);
			
			Boolean isdefault = false;
			
			if( filetype.equals( "fla" ) )
			{
				
				Fla f = new Fla();
				f.setFile( newpath );
				f.setFlashPath( flp.getFlashPath() );
				f.setClose( true );
				f.setVerbose( flp.getVerbose() );
				
				if( justpublish )
				{
					f.setBuild( FuelAntVariables.PUBLISH );
				}
				else
				{
					
					if( def_file != null && def_file.equals( "true" ) && flp.getBuild().equals( FuelAntVariables.TEST ) )
					{
						f.setBuild( FuelAntVariables.TEST );
						defaultfla = f;
						isdefault = true;
					}
					else
					{
						f.setBuild( FuelAntVariables.PUBLISH );
					}
				}
				
				if( !isdefault )
				{
					files.add( f );
				}
				
				//File flaf = new File( newpath );
				//System.out.println( "new path " + newpath + " " + flaf.exists() );
			}
			else if( filetype.equals( "flp" ) )
			{
				Vector<Fla> flpfiles = getFLPFiles(flp, newpath);
				files.addAll( flpfiles );
			}
		}
		
		if( defaultfla != null )
		{
			files.add( defaultfla );
		}
		return( files );
	}
}
